<template>
  <div class="water-content">
    <div class="content" v-for="(item,index) in WaterFish" :key='index'>
      <div class="water-left">
        <img width="30" height="30" :src="require('../../assets/logo.png')">
        <h4>{{item.name}}</h4>
      </div>
      <div class="water-right">
        <p>{{item.text}}</p>
      </div>
    </div>
  </div>
</template>

<script>
import {ref,getCurrentInstance, onMounted,onBeforeUnmount,nextTick} from 'vue'
import { Toast } from 'vant';
export default{
  setup() {
    // 获取全局变量得到$axios
    const {proxy} = getCurrentInstance()
    //触底瀑布的次数
    const WaterNum = ref(1) 
    //处理完成的数组
    const WaterFish = ref([]) 
    // 判断是否正在加载数据
    const isLoading = ref(false)
    //初始化请求数据
    async function initWaterFall(){
      //判断是否正在加载数据
      if(isLoading.value) return;
      //修改检测变量的值
      isLoading.value = true;// 锁的概念一样的
      proxy.$axios.get(`/jokes`).then(res=>{
        if(res.code=='200'){
          // console.log(res.data);
          // WaterFish.value = res.data.result
          WaterFish.value = WaterFish.value.concat(res.data.result,WaterFish.value)
        }else{
          Toast.fail(res.data);
        }
        isLoading.value = false;
      }).catch(err=>{
        isLoading.value = false;
        console.log(err);
      })
    }
    initWaterFall();
    function scrollFun(){
      nextTick(()=>{
        let app = document.getElementsByClassName('water-content')[0]
        let srcollHeight =app.offsetHeight;//页面的高度
        let innerHeight = window.innerHeight//视口的高度
        let scrollTop  = document.documentElement.scrollTop;  //滚动条滚动高度
        // console.log(srcollHeight,innerHeight,scrollTop);
        //距离底部100像素的时候加载更多数据
        if(srcollHeight - innerHeight - scrollTop <= 100){
          console.log(srcollHeight,innerHeight,scrollTop);
          initWaterFall();
        }
      })
    }
    onMounted(()=>{
      window.addEventListener('scroll',scrollFun)
    })
    onBeforeUnmount(()=>{
      window.removeEventListener('scroll',scrollFun)
    })
    return{
      WaterNum,
      WaterFish,
    }
  },
}
</script>
<style lang="less" scoped>
@width1:300px;
@width2:60px;
@width:@width1 + @width2;
.water-content{
  box-sizing: border-box;
  padding: 20px 10px 0px 10px;
  column-count: 2;
  column-gap: 0;
  .content{
    width: @width;
    overflow: hidden;
    box-sizing: border-box;
    break-inside: avoid;
    margin-top: 10px;
    border-radius: 6px;
    border-radius: 10px;
    background: #fff;
    
    height: 100%;
    padding: 10px;
    .water-left{
      display: flex;
      align-items: center;
    }
  }
}

</style>